package com.vogue.family.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.util.Patterns;
import android.widget.Toast;
import com.vogue.family.databinding.ActivitySignUpBinding;
import com.vogue.family.ui.vm.SignUpViewModel;

public class SignUpActivity extends AppCompatActivity {

    private ActivitySignUpBinding binding;
    private SignUpViewModel viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySignUpBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        viewModel = new ViewModelProvider(this).get(SignUpViewModel.class);

        binding.btnSignUp.setOnClickListener(view -> {

            String nickName=binding.etNickName.getText().toString().trim();
            String account=binding.etAccount.getText().toString().trim();
            String email=binding.etEmail.getText().toString().trim();
            String password =binding.etPassword.getText().toString().trim();
            String confirmPassword =binding.etConfirmPassword.getText().toString().trim();

            if (nickName.isEmpty()) {
                Toast.makeText(SignUpActivity.this, "请输入昵称", Toast.LENGTH_SHORT).show();
                return;
            } else if (account.isEmpty()) {
                Toast.makeText(SignUpActivity.this, "请输入账号", Toast.LENGTH_SHORT).show();
                return;
            } else if (email.isEmpty()) {
                Toast.makeText(SignUpActivity.this, "请输入邮箱", Toast.LENGTH_SHORT).show();
                return;
            } else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
                Toast.makeText(SignUpActivity.this, "输入的邮箱无效", Toast.LENGTH_SHORT).show();
                return;
            } else if (password.isEmpty()) {
                Toast.makeText(SignUpActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                return;
            } else if (confirmPassword.trim().isEmpty()) {
                Toast.makeText(SignUpActivity.this, "请确认密码", Toast.LENGTH_SHORT).show();
                return;
            } else if (!password.equals(confirmPassword)) {
                Toast.makeText(SignUpActivity.this, "密码和确认密码必须相同", Toast.LENGTH_SHORT).show();
                return;
            } else {
                viewModel.onSignUp(nickName,account,email,password);
            }
        });

        viewModel.getErrorMsg().observe(this,s -> {
            Toast.makeText(SignUpActivity.this, s, Toast.LENGTH_SHORT).show();
        });

    }
}